<?php

namespace app\crontab;

use zhanshop\App;
use zhanshop\Crontab;

class NginxLogCrontab extends Crontab
{

    public function configure()
    {
        $this->setTitle("每天0点执行一次")->everyday(0);
    }

    public function execute()
    {
        // 复制日志
        $accessPath = App::rootPath().'/docker/nginx/logs/access.log';
        if(file_exists($accessPath)){
            copy(App::rootPath().'/docker/nginx/logs/access.log', App::rootPath().'/docker/nginx/logs/access-'.date('Ymd', strtotime('-1 day')).'.log');

            $files = glob(App::rootPath().'/docker/nginx/logs/access-*.log');
            $fileCount = count($files);
            $delCount = $fileCount - 3;
            if($delCount > 0){
                for($i = 0; $i < $delCount; $i++){
                    @unlink($files[$i]);
                }
            }
            file_put_contents(App::rootPath().'/docker/nginx/logs/access.log', ''); // 清空文件内容
        }


        $accessPath = App::rootPath().'/docker/nginx/logs/herror.log';
        if(file_exists($accessPath)){
            copy(App::rootPath().'/docker/nginx/logs/herror.log', App::rootPath().'/docker/nginx/logs/herror-'.date('Ymd', strtotime('-1 day')).'.log');

            $files = glob(App::rootPath().'/docker/nginx/logs/herror-*.log');
            $fileCount = count($files);
            $delCount = $fileCount - 3;
            if($delCount > 0){
                for($i = 0; $i < $delCount; $i++){
                    @unlink($files[$i]);
                }
            }
            file_put_contents(App::rootPath().'/docker/nginx/logs/herror.log', ''); // 清空文件内容
        }


        $files = glob(App::rootPath().'/docker/nginx/stats/connections-*.log');
        $fileCount = count($files);
        $delCount = $fileCount - 30;
        if($delCount > 0){
            for($i = 0; $i < $delCount; $i++){
                @unlink($files[$i]);
            }
        }

        $files = glob(App::rootPath().'/docker/nginx/stats/stats-*.log');
        $fileCount = count($files);
        $delCount = $fileCount - 30;
        if($delCount > 0){
            for($i = 0; $i < $delCount; $i++){
                @unlink($files[$i]);
            }
        }
    }
}